package com.byb.server.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.byb.server.service.WordKeyService;
import com.byb.server.web.rest.util.HeaderUtil;
import com.byb.server.web.rest.util.PaginationUtil;
import com.byb.server.service.dto.WordKeyDTO;
import io.swagger.annotations.ApiParam;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing WordKey.
 */
@RestController
@RequestMapping("/api")
public class WordKeyResource {

    private final Logger log = LoggerFactory.getLogger(WordKeyResource.class);

    private static final String ENTITY_NAME = "wordKey";

    private final WordKeyService wordKeyService;

    public WordKeyResource(WordKeyService wordKeyService) {
        this.wordKeyService = wordKeyService;
    }

    /**
     * POST  /word-keys : Create a new wordKey.
     *
     * @param wordKeyDTO the wordKeyDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new wordKeyDTO, or with status 400 (Bad Request) if the wordKey has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/word-keys")
    @Timed
    public ResponseEntity<WordKeyDTO> createWordKey(@RequestBody WordKeyDTO wordKeyDTO) throws URISyntaxException {
        log.debug("REST request to save WordKey : {}", wordKeyDTO);
        if (wordKeyDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new wordKey cannot already have an ID")).body(null);
        }
        WordKeyDTO result = wordKeyService.save(wordKeyDTO);
        return ResponseEntity.created(new URI("/api/word-keys/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /word-keys : Updates an existing wordKey.
     *
     * @param wordKeyDTO the wordKeyDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated wordKeyDTO,
     * or with status 400 (Bad Request) if the wordKeyDTO is not valid,
     * or with status 500 (Internal Server Error) if the wordKeyDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/word-keys")
    @Timed
    public ResponseEntity<WordKeyDTO> updateWordKey(@RequestBody WordKeyDTO wordKeyDTO) throws URISyntaxException {
        log.debug("REST request to update WordKey : {}", wordKeyDTO);
        if (wordKeyDTO.getId() == null) {
            return createWordKey(wordKeyDTO);
        }
        WordKeyDTO result = wordKeyService.save(wordKeyDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, wordKeyDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /word-keys : get all the wordKeys.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of wordKeys in body
     */
    @GetMapping("/word-keys")
    @Timed
    public ResponseEntity<List<WordKeyDTO>> getAllWordKeys(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of WordKeys");
        Page<WordKeyDTO> page = wordKeyService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/word-keys");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /word-keys/:id : get the "id" wordKey.
     *
     * @param id the id of the wordKeyDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the wordKeyDTO, or with status 404 (Not Found)
     */
    @GetMapping("/word-keys/{id}")
    @Timed
    public ResponseEntity<WordKeyDTO> getWordKey(@PathVariable Long id) {
        log.debug("REST request to get WordKey : {}", id);
        WordKeyDTO wordKeyDTO = wordKeyService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(wordKeyDTO));
    }

    /**
     * DELETE  /word-keys/:id : delete the "id" wordKey.
     *
     * @param id the id of the wordKeyDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/word-keys/{id}")
    @Timed
    public ResponseEntity<Void> deleteWordKey(@PathVariable Long id) {
        log.debug("REST request to delete WordKey : {}", id);
        wordKeyService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/word-keys?query=:query : search for the wordKey corresponding
     * to the query.
     *
     * @param query the query of the wordKey search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/word-keys")
    @Timed
    public ResponseEntity<List<WordKeyDTO>> searchWordKeys(@RequestParam String query, @ApiParam Pageable pageable) {
        log.debug("REST request to search for a page of WordKeys for query {}", query);
        Page<WordKeyDTO> page = wordKeyService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/word-keys");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

}
